package com.jinke.api.modules.third.hyeus;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jinke.api.common.util.CommonUtil;
import com.jinke.api.modules.app.util.MathUtil;
import com.jinke.api.modules.third.ezeeship.model.request.EstimateRateRequest;
import com.jinke.api.modules.third.ezeeship.util.EzeeShipUtil;
import com.jinke.api.modules.third.hyeus.request.CreateOrderRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.util.Strings;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class HyeusUtil {
    private static String key = "2faa2af4a76aac99bad937ba1fb0a041";
    private static String token = "214WgoUVeyZskflqqIJLwr700bYy40v3ifuNsVxqaVa15QVHaDVRocFhP1grlLuu";
    private static String username = "HYE0074";
//    private static String key = "6e8947545c8cde0a46ff2f2ed12f8b23";
//    private static String token = "8eC1KeQbqW6HA2ragpPTDnmU6u7xxgO5VMPp6YFoqFWOrGCvbujN9yHugnF4lSer";

    public static String sign(String timestamp, String secret) {

        String sign = DigestUtils.md5Hex(secret + '_' + timestamp);
        System.out.println(timestamp + " " + sign);
        return sign;
    }

    public static String sendPostRequest(String url, String requestBody) throws IOException {
        String seq = CommonUtil.getOrderNo();
        log.info("send :  {}, {}", seq, requestBody);
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }

            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestBody.getBytes("UTF-8"));
            }

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("rec :  {}, {}", seq, response.toString());
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        getPrice(getEstimateRateRequest());
    }

    @NotNull
    private static EstimateRateRequest getEstimateRateRequest() {
        // 创建ShippingRequest实例
        EstimateRateRequest shippingRequest = new EstimateRateRequest();

        // 设置from属性
        EstimateRateRequest.Address fromAddress = new EstimateRateRequest.Address();
        fromAddress.setCountryCode("US");
        fromAddress.setStateCode("CA");
        fromAddress.setCity("San Francisco");
        fromAddress.setAddressLine1("215 Clayton St.");
        fromAddress.setAddressLine2("1092,IFC");
        fromAddress.setZipCode("94117");
        shippingRequest.setFrom(fromAddress);

        // 设置to属性
        EstimateRateRequest.Address toAddress = new EstimateRateRequest.Address();
        toAddress.setCountryCode("US");
        toAddress.setStateCode("CA");
        toAddress.setCity("Inglewood");
        toAddress.setAddressLine1("11222 S La Cienega BLVD");
        toAddress.setAddressLine2("1092,IFC");
        toAddress.setZipCode("90304");
        shippingRequest.setTo(toAddress);

        // 设置其余属性
        shippingRequest.setCarrierCode("usps");
        shippingRequest.setServiceCode("FCJ");
        shippingRequest.setIsTest(true);

        // 设置parcels属性
        EstimateRateRequest.Parcel parcel = new EstimateRateRequest.Parcel();
        parcel.setPackageNum(1);
        parcel.setLength("5");
        parcel.setWidth("5");
        parcel.setHeight("5");
        parcel.setDistanceUnit("in");
        parcel.setWeight("4");
        parcel.setMassUnit("lb");
        parcel.setPackageCode("your_package");

        EstimateRateRequest.Extra extra = new EstimateRateRequest.Extra();
        extra.setInsurance(BigDecimal.ZERO);
        extra.setIsCod(false);
        extra.setCodAmount(BigDecimal.ZERO);
        extra.setPaymentMethod("any");
        extra.setDryIceWeight(2);

        parcel.setExtra(extra);

        shippingRequest.setParcels(Arrays.asList(parcel));

        // 打印初始化后的对象
        System.out.println(shippingRequest);
        return shippingRequest;
    }

    public static String getPrice(EstimateRateRequest estimateRateRequest) {
        // 设置API端点URL
        String apiUrl = "http://www.myus56.com/api/v1/order/multi-trial"; // 替换成实际的API URL

        CreateOrderRequest orderRequest = getCreateOrderRequest(estimateRateRequest);
        String requestBody = JSONUtil.toJsonStr(orderRequest);

        try {
            // 发送POST请求
            System.out.println(requestBody);
            String response = sendPostRequest(apiUrl, requestBody);

            // 处理响应
            System.out.println("Response: " + response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    @NotNull
    private static CreateOrderRequest getCreateOrderRequest(EstimateRateRequest estimateRateRequest) {
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setKey(key);
        createOrderRequest.setUsername(username);
        String t = System.currentTimeMillis() / 1000 + "";
        createOrderRequest.setT(t);
        createOrderRequest.setSign(sign(t, token));

        createOrderRequest.setNo(estimateRateRequest.getPlatformNo());
        createOrderRequest.setProduct(estimateRateRequest.getServiceCode());
        createOrderRequest.setFreightClass("");
        createOrderRequest.setIsSignatureService(0);
        createOrderRequest.setNote("");

        EstimateRateRequest.Address to = estimateRateRequest.getTo();
        CreateOrderRequest.Consignee consignee = new CreateOrderRequest.Consignee();
        consignee.setName(to.getPersonName());
        consignee.setPhone(to.getPhone());
        consignee.setAddress(to.getAddressLine1() + ";" + to.getAddressLine2());
        consignee.setStateProvince(to.getStateCode());
        consignee.setCity(to.getCity());
        consignee.setPostcode(to.getZipCode());
        consignee.setCountryCode(to.getCountryCode());
        createOrderRequest.setConsignee(consignee);

        EstimateRateRequest.Address from = estimateRateRequest.getFrom();
        CreateOrderRequest.Consignee sender = new CreateOrderRequest.Consignee();
        sender.setName(from.getPersonName());
        sender.setPhone(from.getPhone());
        sender.setAddress(from.getAddressLine1() + ";" + from.getAddressLine2());
        sender.setStateProvince(from.getStateCode());
        sender.setCity(from.getCity());
        sender.setPostcode(from.getZipCode());
        sender.setCountryCode(from.getCountryCode());
        createOrderRequest.setSender(sender);

        EstimateRateRequest.LabelExtra extra = estimateRateRequest.getExtra();
        if (extra != null) {
            String reference = extra.getReference();
            if (StringUtils.isNotBlank(reference) && StringUtils.isNotEmpty(extra.getReference2())) {
                reference = reference + "; " + extra.getReference2();
            }
            createOrderRequest.setNote(reference);
        }

        List<EstimateRateRequest.Parcel> requestParcels = estimateRateRequest.getParcels();
        List<CreateOrderRequest.Box> parcelsList = requestParcels.stream().map(x -> {
            // 创建Parcels对象
            CreateOrderRequest.Box box = new CreateOrderRequest.Box();
            box.setNumber(x.getPackageNum());

            //  parcels.setBoxnote("label reference");
            BigDecimal weight = BigDecimal.valueOf(Double.parseDouble(x.getWeight()));

            if ("lb".equals(x.getMassUnit())) {
                weight = MathUtil.lb2kg(weight);
            }
            box.setWeight(weight);

            BigDecimal length = BigDecimal.valueOf(Double.parseDouble(x.getLength()));
            BigDecimal width = BigDecimal.valueOf(Double.parseDouble((x.getWidth())));
            BigDecimal height = BigDecimal.valueOf(Double.parseDouble(x.getHeight()));
            if ("in".equals(x.getDistanceUnit())) {
                length = MathUtil.in2cm(weight);
                width = MathUtil.in2cm(weight);
                height = MathUtil.in2cm(weight);
            }
            box.setLength(length);
            box.setWidth(width);
            box.setHeight(height);
            return box;
        }).collect(Collectors.toList());
        createOrderRequest.setBoxes(parcelsList);
        return createOrderRequest;
    }


}
